package com.ai.smlcore.service.impl;

import java.text.DecimalFormat;
import java.util.Date;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.ai.frame.logger.Logger;
import com.ai.frame.logger.LoggerFactory;
import com.ai.smlcore.control.remote.IRemoteService;
import com.ai.smlcore.service.ICacheService;
import com.ai.smlcore.service.common.IQueueService;
import com.ai.smlcore.util.DateUtil;
import com.ai.smlcore.util.StringUtil;
import com.ai.smlcore.util.DateUtil.DATE_PATTERN;

/**
 * 基础服务实现类
 */
public class BaseServiceImpl implements ApplicationContextAware {
	private static final Logger logger = LoggerFactory.getServiceLog(BaseServiceImpl.class);

	private ICacheService cacheService;

	private IQueueService queueService;// 队列服务

	private IRemoteService smlRemoteSV;


	private ApplicationContext applicationContext;

	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	public ApplicationContext getApplicationContext() {
		return this.applicationContext;
	}

	public IRemoteService getSmlRemoteSV() {
		return smlRemoteSV;
	}

	public void setSmlRemoteSV(IRemoteService smlRemoteSV) {
		this.smlRemoteSV = smlRemoteSV;
	}

	public ICacheService getCacheService() {
		return cacheService;
	}

	public void setCacheService(ICacheService cacheService) {
		this.cacheService = cacheService;
	}

	public IQueueService getQueueService() {
		return queueService;
	}

	public void setQueueService(IQueueService queueService) {
		this.queueService = queueService;
	}


	/**
	 * 主键生成策略
	 * 
	 * @param tableName
	 *            需要获取主键的表名
	 */
	public String getSequence(String tableName) {
		if (StringUtil.isEmpty(tableName)) {
			throw new RuntimeException("获取主键时前缀不能为空!建议传入表名");
		}
		String redisKey = "REDIS_TBL_" + tableName;
		String id = null;
		try {
			logger.info("开始获取主键 ", "key=" + redisKey);
			id = DateUtil.date2String(new Date(), DATE_PATTERN.YYYYMMDDHHMMSSSSS) + ""
					+ new DecimalFormat("#000").format(getCacheService().incr(redisKey));
			logger.info("获取主键成功", "id=" + id);
		} catch (Exception e) {
			logger.error("使用redis获取主键失败，开始使用随机数", "key=" + redisKey, e);
			id = DateUtil.date2String(new Date(), DATE_PATTERN.YYYYMMDDHHMMSSSSS) + ""
					+ new DecimalFormat("#000").format(RandomUtils.nextInt(1, 1000));
			logger.error("NOT ERROR! 主键获取成功", "key=" + redisKey + ",id=" + id);
		}
		return id;
	}


}
